#ifndef PORTMANAGER_H
#define PORTMANAGER_H

#include "portdefine.h"
#include "singleton.h"
#include "basemanager.h"
#include "baseport.h"
#include "serialport.h"
#include "configdefine.h"

class PortManager : public BaseManager
{
    Q_OBJECT
public:
    struct SerialPortConfig
    {
        QString 		label = "";

        ConfigKey		autoOpen;
        ConfigKey		name;
        ConfigKey		baudRate;
        ConfigKey		dataBits;
        ConfigKey		stopBits;
        ConfigKey		parity;

        SerialPortConfig(QString _label = "",
                         ConfigKey _autoOpen = CK_DebugUart_AutoOpen,
                         ConfigKey _name = CK_DebugUart_Name,
                         ConfigKey _baudRate = CK_DebugUart_BaudRate,
                         ConfigKey _dataBits = CK_DebugUart_DataBits,
                         ConfigKey _stopBits = CK_DebugUart_StopBits,
                         ConfigKey _parity = CK_DebugUart_Parity)
        {
            label = _label;
            autoOpen = _autoOpen;
            name = _name;
            baudRate = _baudRate;
            dataBits = _dataBits;
            stopBits = _stopBits;
            parity = _parity;
        }
    };

    PortManager(QObject *parent = nullptr);
    virtual ~PortManager();

    bool attach(BasePort *port);
    bool detach(BasePort *port);

    void print();

    BasePort *find(QString &name);
    BasePort *find(PortID id);
    BasePort *find(uint magic);

    QList<BasePort *> getAllPorts();

    uint createMagic(QString str);

public slots:
    void onStart(void);

signals:
    void started();

public:
    bool saveSerialPort(PortID id, SerialPortSetting &setting);
    SerialPortConfig getSerialPortConfig(PortID id);

protected:
    bool initSerialPort(PortID id);
    void checkSerialPortAutoOpen();

private:
    QMutex				            *m_mutex = nullptr;
    QMap<uint, BasePort*>           m_ports;

    QMap<uint, SerialPortConfig>	m_serialPortConfig;

    SINGLETON_DECLARE(PortManager)
};

#define portManager PortManager::getInstance()

#endif // PORTMANAGER_H
